var j$ = jQuery.noConflict();

j$(document).ready(function () {

    /* Building the accordion widget */
    j$('#accordion').accordion({
        autoHeight: false,
        navigation: true,
        collapsible: true
    });

    var iconDiv = j$('<div></div>').addClass('ui-icon ui-icon-circle-triangle-e').css('float', 'left');

    j$('.toggler').prepend(iconDiv).css({
        'cursor': 'hand',
        'cursor': 'pointer',
        'clear': 'both'
    }).click(function () {
        if (j$(this).is('h5')) {
            j$('h5.toggler').not(this).next().hide();
            j$('h5.toggler').not(this).find('div').removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-e");
        } else {
            j$('.toggler').not(this).next().hide();
            j$('.toggler').not(this).find('div').removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-e");
        }
        j$(this).next().toggle();
        if (j$(this).find('div').hasClass("ui-icon-circle-triangle-s")) {
            j$(this).find('div').removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-e");
        } else {
            j$(this).find('div').removeClass("ui-icon-circle-triangle-e").addClass("ui-icon-circle-triangle-s");
        }
    });

    /* TO SUPPORT DISPLAY IN SFDC */
    j$('h3, h4, h5').css('display', 'block');

    j$('.toggleable').hide(); /* Building the accordion widget */

    /* HEX INPUTS */
    j$('.hex').validHex().keyup(function () {
        j$(this).validHex();
    });

    /********FORM PROPERTIES************/

    /*Frame*/

    /*Header*/
    j$('#frameheadercolor__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function (event, ui) {
            j$("#mw2cWrapper #mw2cTitleContainer").css('background-color', j$("#frameheadercolor__c").val());
            j$("#mw2cWrapper #mw2cTitle").css('height', '50px');
        }
    });

    j$("#frameHeaderCornerRoundness").slider({
        value: 0,
        min: 0,
        max: 20,
        step: 1,
        slide: function (event, ui) {
            j$("#frameheaderradius__c").html(ui.value + 'px');
            j$("#mw2cTitleContainer").css({
                "border-radius": ui.value + 'px',
                "-moz-border-radius": ui.value + 'px',
                "-ms-border-radius": ui.value + 'px',
                "-webkit-border-radius": ui.value + 'px'
            });
        },
        change: function (event, ui) {
            j$("#frameheaderradius__c").html(ui.value + 'px');
            j$("#mw2cTitleContainer").css({
                "border-radius": ui.value + 'px',
                "-moz-border-radius": ui.value + 'px',
                "-ms-border-radius": ui.value + 'px',
                "-webkit-border-radius": ui.value + 'px'
            });
        }
    });
    j$("#frameheaderradius__c").html(j$("#frameHeaderCornerRoundness").slider("value") + "px"); /*Header*/

    /*Title*/
    j$("#frametitlealign__c").change(function () {
        j$("#mw2cTitle").css('text-align', j$(this).val());
    }); /*Title*/

    /*Border*/
    j$("#frameborderstyle__c").change(function () {
        j$("#mw2cWrapper").css('border-style', j$(this).val());
        if (j$(this).val() == 'None') {
            j$("#frameBorderSize, #frameCornerRoundness").slider("disable");
            j$('#framebordercolor__c').attr('disabled', 'disabled').next().attr('disabled', 'disabled');
        } else {
            j$("#frameBorderSize, #frameCornerRoundness").slider("enable");
            j$('#framebordercolor__c').removeAttr('disabled').next().removeAttr('disabled');
        }
    });

    j$("#frameBorderSize").slider({
        value: 1,
        min: 1,
        max: 10,
        step: 1,
        slide: function (event, ui) {
            j$("#mw2cWrapper").css("border-width", ui.value + 'px');
            j$("#framebordersize__c").html(ui.value + 'px');
        },
        change: function (event, ui) {
            j$("#mw2cWrapper").css("border-width", ui.value + 'px');
            j$("#framebordersize__c").html(ui.value + 'px');
        }
    });
    j$("#mw2cWrapper").css("border-width", j$("#frameBorderSize").slider("value") + 'px');
    j$("#framebordersize__c").html(j$("#frameBorderSize").slider("value") + "px");

    j$("#frameCornerRoundness").slider({
        value: 0,
        min: 0,
        max: 20,
        step: 1,
        slide: function (event, ui) {
            j$("#frameborderradius__c").html(ui.value + 'px');
            j$("#mw2cWrapper").css({
                "border-radius": ui.value + 'px',
                "-moz-border-radius": ui.value + 'px',
                "-ms-border-radius": ui.value + 'px',
                "-webkit-border-radius": ui.value + 'px'
            });
        },
        change: function (event, ui) {
            j$("#frameborderradius__c").html(ui.value + 'px');
            j$("#mw2cWrapper").css({
                "border-radius": ui.value + 'px',
                "-moz-border-radius": ui.value + 'px',
                "-ms-border-radius": ui.value + 'px',
                "-webkit-border-radius": ui.value + 'px'
            });
        }
    });
    j$("#frameborderradius__c").html(j$("#frameCornerRoundness").slider("value") + "px");
    j$("#mw2cWrapper").css({
        "border-radius": j$("#frameCornerRoundness").slider("value") + 'px',
        "-moz-border-radius": j$("#frameCornerRoundness").slider("value") + 'px',
        "-ms-border-radius": j$("#frameCornerRoundness").slider("value") + 'px',
        "-webkit-border-radius": j$("#frameCornerRoundness").slider("value") + 'px'
    });

    j$("#frameBorderSize, #frameCornerRoundness").slider("disable");

    j$('#framebordercolor__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cWrapper").css('border-color', j$("#framebordercolor__c").val());
        }
    });
    j$('#framebordercolor__c').attr('disabled', 'disabled').next().attr('disabled', 'disabled');

    /*Border*/

    /*Frame*/

    /*Background*/
    j$('#backgroundcolor__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function (event, ui) {
            j$("#mw2cWrapper").css('background-color', j$("#backgroundcolor__c").val());
        }
    });

    buildCustomDropDown('backgroundgradient__c');
    j$("#targetbackgroundgradient__c.dropdown dd ul li a").click(function () {
        var text = j$(this).html();
        var source = j$('#backgroundgradient__c');
        j$("#targetbackgroundgradient__c.dropdown dt a").html(text);
        j$("#targetbackgroundgradient__c.dropdown dd ul").hide('blind');

        source.val(j$(this).find("span.value").html());
        j$('#mw2cWrapper').css('background', j$('#backgroundcolor__c').val() + ' ' + source.find('option:selected').data('image'));
    });
   /*Background*/

    /*Form Buttons*/
    buildCustomDropDown('formbuttonsstyle__c');

    j$("#targetformbuttonsstyle__c.dropdown dd ul li a").click(function () {
        var text = j$(this).html();
        var source = j$('#formbuttonsstyle__c');
        j$("#targetformbuttonsstyle__c.dropdown dt a").html(text);
        j$("#targetformbuttonsstyle__c.dropdown dd ul").hide('blind');

        source.val(j$(this).find("span.value").html());

        j$("#mw2cButtons input").attr('style', '');
        if (source.val() != 'standard') { /* JQUERY CLASS .ui-button */
            j$("#mw2cButtons input").css({
                'display': 'inline-block',
                'position': 'relative',
                'margin-right': '.1em',
                'text-decoration': 'none !important',
                'cursor': 'pointer',
                'text-align': 'center',
                'zoom': '1',
                'overflow': 'visible',
                '-moz-border-radius': '4px',
                '-webkit-border-radius': '4px',
                '-khtml-border-radius': '4px',
                'border-radius': '4px',
                //'font-family': 'Verdana,Arial,sans-serif',
                //'font-size': '1.1em',
                'padding': '.4em 1em'
            });
            
            j$('#fontsfamilybuttontext__c').val('Verdana, Arial, sans-serif').trigger('change');
            j$('#buttonTextFontSize').slider('value', 1.1);
            j$('#fontscolorbuttontext__c').val('#ffffff');
            j$('#fontsstylebuttontextbold__c, #fontsstylebuttontextsmallcaps__c, #fontsstylebuttontextitalic__c').removeAttr('checked');

            if (source.val() != 'plain') {
                var option = j$(source).find('option:selected');
                j$("#mw2cButtons input").css({
                    'font-weight': 'normal',
                    'color': '#' + option.data('font-color'),
                    'border': '1px solid ' + '#' + option.data('border-color'),
                    'background': 'url(' + option.data('image') + ') repeat-x scroll 50% 50% ' + '#' + option.data('background-color')
                });
                j$('#fontscolorbuttontext__c').val('#' + option.data('font-color'));
            }
        }
    });

    j$("#formbuttonsalign__c").change(function () {
        j$("#mw2cButtons").css('text-align', j$(this).val());
    });

    j$("#formbuttonssubmittext__c").keyup(function () {
        j$('#mw2cButtons input[id=buttonSubmit]').val(j$(this).val());
    });

    j$("#formbuttonsresetchecked__c").change(function () {
        if (j$(this).is(':checked')) {
            j$('#formbuttonsresettext__c').removeAttr('disabled').focus();
            var toAppend = j$('<input />').attr({
                type: "reset",
                id: "buttonReset",
                value: j$('#formbuttonsresettext__c').val(),
                style: j$("#buttonSubmit").attr('style')
            });
            j$("#mw2cButtons").append(toAppend);
        } else {
            j$("#formbuttonsresettext__c").attr("disabled", "disabled");
            j$('#mw2cButtons input[id="buttonReset"]').remove();
        }
    });

    j$("#formbuttonsresettext__c").keyup(function () {
        j$('#mw2cButtons input[id="buttonReset"]').val(j$(this).val());
    });

    /*Form Buttons*/

    /*Required Field Legend*/

    j$("#requiredfieldslegendtext__c").keyup(function () {
        j$("#mw2cRequiredMessage").html(j$(this).val());
    });
    j$("#requiredfieldslegendtext__c").val(j$("#mw2cRequiredMessage").html().trim());

    j$("#requiredfieldslegendalign__c").change(function () {
        j$("#mw2cRequiredMessage").css("text-align", j$(this).val());
    });

    j$("#requiredfieldslegendposition__c").change(function () {
        if (j$(this).val() == "Bottom") {
            j$("#mw2cFields").after(j$("#mw2cRequiredMessage"));
        } else {
            j$("#mw2cFields").before(j$("#mw2cRequiredMessage"));
        }
    });

    /*Required Field Legend*/
   
   /*Captcha Legend*/
  j$("#captchalegendtext__c").keyup(function () {
        j$("#mw2cCaptchaLabel").html(j$(this).val());
    });
    j$("#captchalegendtext__c").val(j$("#mw2cCaptchaLabel").html().trim());
  /*Captcha Legend*/

    /********FORM PROPERTIES************/

    /********FORM FONTS************/

    /*Family*/

    j$("#fontsfamilytitle__c").change(function () {
        setFontFamily(j$("#mw2cTitle"), j$(this).val());
    });

    j$("#fontsfamilyrequiredfieldslegend__c").change(function () {
        setFontFamily(j$("#mw2cRequiredMessage"), j$(this).val());
    });

    j$("#fontsfamilyinputlabels__c").change(function () {
        setFontFamily(j$("#mw2cFields label"), j$(this).val());
    });

    j$("#fontsfamilyinputtext__c").change(function () {
        setFontFamily(j$("#mw2cFields, #mw2cImages").find('input, select, textarea'), j$(this).val());
    });

    j$("#fontsfamilybuttontext__c").change(function () {
        setFontFamily(j$("#mw2cButtons input"), j$(this).val());
    });

    function setFontFamily(element, value) {
        j$(element).css("font-family", value);
    }

    /*Family*/

    /*Size*/

    j$("#frameTitleSize").slider({
        value: 1,
        min: 0.5,
        max: 2.5,
        step: 0.1,
        slide: function (event, ui) {
            j$("#fontssizetitle__c").html(ui.value + 'em');
            j$("#mw2cTitle").css("font-size", ui.value + "em");
        },
        change: function (event, ui) {
            j$("#fontssizetitle__c").html(ui.value + 'em');
            j$("#mw2cTitle").css("font-size", ui.value + "em");
        }
    });
    j$("#fontssizetitle__c").html(j$("#frameTitleSize").slider("value") + "em");
    j$("#mw2cTitle").css("font-size", j$("#frameTitleSize").slider("value") + "em");

    j$("#frameReqFldsLegSize").slider({
        value: 1,
        min: 0.5,
        max: 2.5,
        step: 0.1,
        slide: function (event, ui) {
            j$("#mw2cRequiredMessage").css("font-size", ui.value + 'em');
            j$("#fontssizerequiredfieldslegend__c").html(ui.value + "em");
        },
        change: function (event, ui) {
            j$("#mw2cRequiredMessage").css("font-size", ui.value + 'em');
            j$("#fontssizerequiredfieldslegend__c").html(ui.value + "em");
        }
    });
    j$("#fontssizerequiredfieldslegend__c").html(j$("#frameReqFldsLegSize").slider("value") + "em");
    j$("#mw2cRequiredMessage").css("font-size", j$("#frameReqFldsLegSize").slider("value") + 'em');

    j$("#frameFontSize").slider({
        value: 1,
        min: 0.5,
        max: 2.5,
        step: 0.1,
        slide: function (event, ui) {
            j$("#fontssizeinputlabels__c").html(ui.value + 'em');
            j$("#mw2cFields").find("label").css("font-size", ui.value + 'em');
        },
        change: function (event, ui) {
            j$("#fontssizeinputlabels__c").html(ui.value + 'em');
            j$("#mw2cFields").find("label").css("font-size", ui.value + 'em');
        }
    });
    j$("#fontssizeinputlabels__c").html(j$("#frameFontSize").slider("value") + "em");
    j$("#mw2cFields").find("label").css("font-size", j$("#frameFontSize").slider("value") + 'em');

    j$("#frameInpTextFontSize").slider({
        value: 1,
        min: 0.5,
        max: 2.5,
        step: 0.1,
        slide: function (event, ui) {
            j$("#fontssizeinputtext__c").html(ui.value + 'em');
            j$("#mw2cFields, #mw2cImages").find("input, select, textarea").css("font-size", ui.value + 'em');
        },
        change: function (event, ui) {
            j$("#fontssizeinputtext__c").html(ui.value + 'em');
            j$("#mw2cFields, #mw2cImages").find("input, select, textarea").css("font-size", ui.value + 'em');
        }
    });

    j$("#fontssizeinputtext__c").html(j$("#frameInpTextFontSize").slider("value") + "em");
    j$("#mw2cFields, #mw2cImages").find("input, select, textarea").css("font-size", j$("#frameInpTextFontSize").slider("value") + 'em');

    j$("#buttonTextFontSize").slider({
        value: 1,
        min: 0.5,
        max: 2.5,
        step: 0.1,
        slide: function (event, ui) {
            j$("#fontssizebuttontext__c").html(ui.value + 'em');
            j$("#mw2cButtons input").css("font-size", ui.value + "em");
        },
        change: function (event, ui) {
            j$("#fontssizebuttontext__c").html(ui.value + 'em');
            j$("#mw2cButtons input").css("font-size", ui.value + "em");
        }
    });

    j$("#fontssizebuttontext__c").html(j$("#buttonTextFontSize").slider('value') + 'em');

    /*Size*/

    /*Color*/

    j$('#fontscolortitle__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cTitle").css('color', j$('#fontscolortitle__c').val());
        }
    });

    j$('#fontscolorrequiredfieldslegend__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cRequiredMessage, div.label span").css('color', j$('#fontscolorrequiredfieldslegend__c').val());
        }
    });

    j$('#fontscolorinputlabels__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cFields label").css('color', j$('#fontscolorinputlabels__c').val());
        }
    });

    j$('#fontscolorinputtext__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cFields, #mw2cImages").find("input,textarea,select").css('color', j$('#fontscolorinputtext__c').val());
        }
    });

    j$('#fontscolorbuttontext__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cButtons input").css("color", j$('#fontscolorbuttontext__c').val());
        }
    }); /*Color*/

    /*Style*/

    j$("#fontsstyletitlebold__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontWeight(j$("#mw2cTitle"), 'Bold');
        } else {
            setFontWeight(j$("#mw2cTitle"), 'Normal');
        }
    });

    j$("#fontsstyletitlesmallcaps__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontVariant(j$("#mw2cTitle"), 'Small-caps');
        } else {
            setFontVariant(j$("#mw2cTitle"), 'Normal');
        }
    });

    j$("#fontsstyletitleitalic__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontStyle(j$("#mw2cTitle"), 'Italic');
        } else {
            setFontStyle(j$("#mw2cTitle"), 'Normal');
        }
    });

    j$("#fontsstylerequiredfieldslegendbold__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontWeight(j$("#mw2cRequiredMessage"), 'Bold');
        } else {
            setFontWeight(j$("#mw2cRequiredMessage"), 'Normal');
        }
    });

    j$("#fontsstylerequiredfieldslegendsmallcaps__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontVariant(j$("#mw2cRequiredMessage"), 'Small-caps');
        } else {
            setFontVariant(j$("#mw2cRequiredMessage"), 'Normal');
        }
    });

    j$("#fontsstylerequiredfieldslegenditalic__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontStyle(j$("#mw2cRequiredMessage"), 'Italic');
        } else {
            setFontStyle(j$("#mw2cRequiredMessage"), 'Normal');
        }
    });

    j$("#fontsstylelabelsbold__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontWeight(j$("#mw2cFields label"), 'Bold');
        } else {
            setFontWeight(j$("#mw2cFields label"), 'Normal');
        }
    });

    j$("#fontsstylelabelssmallcaps__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontVariant(j$("#mw2cFields label"), 'Small-caps');
        } else {
            setFontVariant(j$("#mw2cFields label"), 'Normal');
        }
    });

    j$("#fontsstylelabelsitalic__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontStyle(j$("#mw2cFields label"), 'Italic');
        } else {
            setFontStyle(j$("#mw2cFields label"), 'Normal');
        }
    });

    j$("#fontsstyleinputtextbold__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontWeight(j$("#mw2cFields input,#mw2cImages input,#mw2cFields select,#mw2cFields textarea"), 'Bold');
        } else {
            setFontWeight(j$("#mw2cFields input,#mw2cImages input,#mw2cFields select,#mw2cFields textarea"), 'Normal');
        }
    });

    j$("#fontsstyleinputtextsmallcaps__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontVariant(j$("#mw2cFields input,#mw2cImages input,#mw2cFields select,#mw2cFields textarea"), 'Small-caps');
        } else {
            setFontVariant(j$("#mw2cFields input,#mw2cImages input,#mw2cFields select,#mw2cFields textarea"), 'Normal');
        }
    });

    j$("#fontsstyleinputtextitalic__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontStyle(j$("#mw2cFields input,#mw2cImages input,#mw2cFields select,#mw2cFields textarea"), 'Italic');
        } else {
            setFontStyle(j$("#mw2cFields input,#mw2cImages input,#mw2cFields select,#mw2cFields textarea"), 'Normal');
        }
    });

    j$("#fontsstylebuttontextbold__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontWeight(j$("#mw2cButtons input"), 'Bold');
        } else {
            setFontWeight(j$("#mw2cButtons input"), 'Normal');
        }
    });

    j$("#fontsstylebuttontextsmallcaps__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontVariant(j$("#mw2cButtons input"), 'Small-caps');
        } else {
            setFontVariant(j$("#mw2cButtons input"), 'Normal');
        }
    });

    j$("#fontsstylebuttontextitalic__c").change(function () {
        if (j$(this).is(":checked")) {
            setFontStyle(j$("#mw2cButtons input"), 'Italic');
        } else {
            setFontStyle(j$("#mw2cButtons input"), 'Normal');
        }
    });

    function setFontWeight(element, value) {
        j$(element).css("font-weight", value);
    }

    function setFontVariant(element, value) {
        j$(element).css("font-variant", value);
    }

    function setFontStyle(element, value) {
        j$(element).css("font-style", value);
    }

    /*Style*/

    /********FORM FONTS************/

    /********FORM LAYOUTS************/

    j$('#block').change(function () {
        j$('input[name="layoutalign__c"]').attr('disabled', 'disabled');
        j$('#left').attr('checked', 'checked');
        j$('#mw2cFields div.label').css({
            'float': '',
            'clear': '',
            'width': '',
            'text-align': '',
            'display': 'block'
        });
        j$('div.msg').css('margin-left', '');
    });
    j$('#inline').change(function () {
        j$('input[name="layoutalign__c"]').removeAttr('disabled');
        j$('#mw2cFields div.label').css({
            'float': 'left',
            'clear': 'left',
            'width': '40%',
            'display': 'inline'
        });
        j$('div.msg').css('margin-left', j$('div.label').width() + 'px');
    });
    j$('input[name="layoutalign__c"]').attr('disabled', 'disabled');
    j$('#left').change(function () {
        j$('#mw2cFields div.label').css('text-align', '');
    });
    j$('#right').change(function () {
        j$('#mw2cFields div.label').css('text-align', 'right');
    });
    j$('#column_1').change(function () {
        j$('input[name="layoutsortorder__c"]').attr('disabled', 'disabled');
        j$('#sortOrder_h').attr('checked', 'checked');
        j$('#mw2cFields').html(horizontalOrder);
        j$('#mw2cFields div.field').css({
            'float': '',
            'width': ''
        });
        if (j$('#inline').is(':checked')) {
            j$('div.msg').css('margin-left', j$('div.label').width() + 'px');
        }
    });
    j$('#column_2').change(function () {
        j$('input[name="layoutsortorder__c"]').removeAttr('disabled');
        j$('#mw2cFields div.field').css({
            'float': 'left',
            'width': '50%'
        });
        if (j$('#inline').is(':checked')) {
            j$('div.msg').css('margin-left', j$('div.label').width() + 'px');
        }
        if (j$('#mw2cFields div.field').length % 2 != 0) {
            j$('#mw2cFields div.field:last-child').after('<div style="clear:both"></div>');
        }
        j$('#mw2cFields div.field:nth-child(2n+2)').after('<div style="clear:both"></div>');
    });
    j$('input[name="layoutsortorder__c"]').attr('disabled', 'disabled');
    j$('#sortOrder_h').change(function () {
        j$('#mw2cFields').html(horizontalOrder);
        if (j$('#mw2cFields div.field').length % 2 != 0) {
            j$('#mw2cFields div.field:last-child').after('<div style="clear:both"></div>');
        }
        j$('#mw2cFields div.field:nth-child(2n+2)').after('<div style="clear:both"></div>');
    });
    j$('#sortOrder_v').change(function () {
        if (verticalOrder == null) {
            verticalOrder = getVerticalOrder(horizontalOrder);
        }
        j$('#mw2cFields').html(verticalOrder);
        if (j$('#mw2cFields div.field').length % 2 != 0) {
            j$('#mw2cFields div.field:last-child').after('<div style="clear:both"></div>');
        }
        j$('#mw2cFields div.field:nth-child(2n+2)').after('<div style="clear:both"></div>');
    });

    var horizontalOrder = j$('#mw2cFields div.field');
    var verticalOrder;

    function getVerticalOrder(divs) {
        var reOrdered = new Array();
        var half = Math.round(divs.length / 2);
        for (var i = 0; i < half; i++) {
            reOrdered.push(divs[i]);
            if (divs[half + i] != null) {
                reOrdered.push(divs[half + i]);
            }
        }
        return reOrdered;
    }

    /********FORM LAYOUTS************/

    /********INPUTS PROPERTIES*******/

    /***Border***/

    j$("#inputsborderstyle__c").change(function () {
        j$("#mw2cWrapper").find("input[type='text'],textarea,select").css('border-style', j$(this).val());
        if (j$(this).val() == 'None') {
            j$("#inputsBorderSize, #inputsCornerRoundness").slider("disable");
            j$('#inputsbordercolor__c').attr('disabled', 'disabled').next().attr('disabled', 'disabled');
        } else {
            j$("#inputsBorderSize, #inputsCornerRoundness").slider("enable");
            j$('#inputsbordercolor__c').removeAttr('disabled').next().removeAttr('disabled');
        }
    });

    j$("#inputsBorderSize").slider({
        value: 1,
        min: 1,
        max: 6,
        step: 1,
        slide: function (event, ui) {
            j$("#inputsbordersize__c").html(ui.value + 'px');
            j$("#mw2cFields, #mw2cImages").find("input,textarea,select").css('border-width', ui.value + 'px');
        },
        change: function (event, ui) {
            j$("#inputsbordersize__c").html(ui.value + 'px');
            j$("#mw2cFields, #mw2cImages").find("input,textarea,select").css('border-width', ui.value + 'px');
        }
    });
    j$("#inputsbordersize__c").html(j$("#inputsBorderSize").slider("value") + "px");


    j$("#inputsCornerRoundness").slider({
        value: 0,
        min: 0,
        max: 10,
        step: 1,
        slide: function (event, ui) {
            j$("#inputsborderradius__c").html(ui.value + 'px');
            j$("#mw2cFields, #mw2cImages").find("input,textarea,select").css({
                "border-radius": ui.value + 'px',
                "-moz-border-radius": ui.value + 'px',
                "-ms-border-radius": ui.value + 'px',
                "-webkit-border-radius": ui.value + 'px'
            });
        },
        change: function (event, ui) {
            j$("#inputsborderradius__c").html(ui.value + 'px');
            j$("#mw2cFields, #mw2cImages").find("input,textarea,select").css({
                "border-radius": ui.value + 'px',
                "-moz-border-radius": ui.value + 'px',
                "-ms-border-radius": ui.value + 'px',
                "-webkit-border-radius": ui.value + 'px'
            });
        }
    });
    j$("#inputsborderradius__c").html(j$("#inputsCornerRoundness").slider("value") + "px");


    j$('#inputsbordercolor__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cWrapper").find("input[type='text'],textarea,select").css('border-color', j$("#inputsbordercolor__c").val());
        }
    }); /***Border***/

    /***Background***/

    j$('#inputsbackgroundcolor__c').modcoder_excolor({
        hue_slider: 9,
        sb_slider: 1,
        round_corners: false,
        shadow: false,
        backlight: false,
        callback_on_ok: function () {
            j$("#mw2cWrapper").find("input[type='text'],textarea,select").css('background-color', j$("#inputsbackgroundcolor__c").val());
        }
    });

    /***Background***/

    /***Size***/

    j$("#inputTextSizeWidth").slider({
        value: 150,
        min: 150,
        max: 300,
        step: 10,
        slide: function (event, ui) {
            j$("#inputssizetextwidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper input[type='text']").css('width', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizetextwidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper input[type='text']").css('width', ui.value);
        }
    });
    j$("#inputssizetextwidth__c").html(j$("#inputTextSizeWidth").slider("value") + "px");

    j$("#inputTextSizeHeight").slider({
        value: 20,
        min: 20,
        max: 50,
        step: 5,
        slide: function (event, ui) {
            j$("#inputssizetextheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper input[type='text']").css('height', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizetextheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper input[type='text']").css('height', ui.value);
        }
    });
    j$("#inputssizetextheight__c").html(j$("#inputTextSizeHeight").slider("value") + "px");

    j$("#inputTextAreaSizeWidth").slider({
        value: 150,
        min: 150,
        max: 300,
        step: 10,
        slide: function (event, ui) {
            j$("#inputssizetextareawidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper textarea").css('width', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizetextareawidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper textarea").css('width', ui.value);
        }
    });
    j$("#inputssizetextareawidth__c").html(j$("#inputTextAreaSizeWidth").slider("value") + "px");

    j$("#inputTextAreaSizeHeight").slider({
        value: 30,
        min: 30,
        max: 300,
        step: 10,
        slide: function (event, ui) {
            j$("#inputssizetextareaheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper textarea").css('height', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizetextareaheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper textarea").css('height', ui.value);
        }
    });
    j$("#inputssizetextareaheight__c").html(j$("#inputTextAreaSizeHeight").slider("value") + "px");

    j$("#inputSelectSizeWidth").slider({
        value: 150,
        min: 150,
        max: 300,
        step: 10,
        slide: function (event, ui) {
            j$("#inputssizeselectwidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper select:not('[multiple]')").css('width', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizeselectwidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper select:not('[multiple]')").css('width', ui.value);
        }
    });
    j$("#inputssizeselectwidth__c").html(j$("#inputSelectSizeWidth").slider("value") + "px");

    j$("#inputSelectSizeHeight").slider({
        value: 20,
        min: 20,
        max: 50,
        step: 5,
        slide: function (event, ui) {
            j$("#inputssizeselectheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper select:not('[multiple]')").css('height', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizeselectheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper select:not('[multiple]')").css('height', ui.value);
        }
    });
    j$("#inputssizeselectheight__c").html(j$("#inputSelectSizeHeight").slider("value") + "px");

    j$("#inputMultiSelectSizeWidth").slider({
        value: 150,
        min: 150,
        max: 300,
        step: 10,
        slide: function (event, ui) {
            j$("#inputssizemultiselectwidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper select[multiple='multiple']").css('width', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizemultiselectwidth__c").html(ui.value + 'px');
            j$("#mw2cWrapper select[multiple='multiple']").css('width', ui.value);
        }
    });
    j$("#inputssizemultiselectwidth__c").html(j$("#inputMultiSelectSizeWidth").slider("value") + "px");

    j$("#inputMultiSelectSizeHeight").slider({
        value: 30,
        min: 30,
        max: 300,
        step: 10,
        slide: function (event, ui) {
            j$("#inputssizemultiselectheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper select[multiple='multiple']").css('height', ui.value);
        },
        change: function (event, ui) {
            j$("#inputssizemultiselectheight__c").html(ui.value + 'px');
            j$("#mw2cWrapper select[multiple='multiple']").css('height', ui.value);
        }
    });
    j$("#inputssizemultiselectheight__c").html(j$("#inputMultiSelectSizeHeight").slider("value") + "px");

    /***Size***/

    /********INPUTS PROPERTIES*******/
   
   
  var qs = j$('input[id$="qstring"]').val();
  if(qs != ''){
    var props = qs.split('&');
    
    for(var i = 0; i < props.length; i++){
      var k = props[i].split('=')[0];
      var v = props[i].split('=')[1];
      
      var obj = j$('#'+k);
      if(obj.is('input[type="text"]') || obj.is('select')){
        if(obj.hasClass('hex')) {
          obj.val(v);
          obj.click();
          setTimeout( function(){j$('#modcoder_ok').click();}, 50);
        } else if(obj.hasClass('custom-dd')) {
          var elem = j$('#target'+obj.attr('id'));
          elem.find('dd ul li a span.value:contains("'+v+'")').each(function() {
            if(j$(this).html() == v) j$(this).click();
          });
        } else {
          obj.val(v);
          obj.trigger('change');
          obj.trigger('keyup');
          obj.trigger('blur');
        }
      } else if(obj.is('span')){
        obj.html(v);
        var elem = obj.parent('label').next('div.slider');
        elem.slider('value', v.replace('em', '').replace('px',''));
      } else if(obj.is(':checkbox')) {
        if(v == 'false' || v == '') obj.removeAttr('checked');
        else obj.attr('checked', 'checked');
        obj.trigger('change');
      } else {
        var elems = j$('input[type="radio"][name="'+k+'"]');

        elems.filter('input[value="'+v+'"]').attr('checked', 'checked');
      }
    }
    
    j$('input[name="layoutdisplay__c"]:checked').trigger('change');
    j$('input[name="layoutalign__c"]:checked').trigger('change');
    j$('input[name="layoutcolumn__c"]:checked').trigger('change');
    j$('input[name="layoutsortorder__c"]:checked').trigger('change');
    if (j$('#inline').is(':checked')) {
      j$('div.msg').css('margin-left', j$('div.label').width() + 'px');
    }
  } // END qstring parse / triggers
}); //END of document ready

/**** UTIL FUNCTIONS ****/
/* validation for hex inputs */
j$.fn.validHex = function () {
    return this.each(function () {
        var value = j$(this).val();
        // non [#a-f0-9]
        value = value.replace(/[^#a-fA-F0-9]/g, '');
        value = value.toLowerCase();
        if (value.match(/#/g) && value.match(/#/g).length > 1)
        // ##
        value = value.replace(/#/g, '');
        if (value.indexOf('#') == -1)
        // no #
        value = '#' + value;
        if (value.length > 7)
        // too many chars
        value = value.substr(0, 7);
        j$(this).val(value);
    });
};

function hex2rgb(hexStr) {
    // note: hexStr should be #rrggbb
    var hex = parseInt(hexStr.substring(1), 16);
    var r = (hex & 0xff0000) >> 16;
    var g = (hex & 0x00ff00) >> 8;
    var b = hex & 0x0000ff;
    return r + ',' + g + ',' + b;
}

function buildCustomDropDown(elem) {
    var source = j$('#' + elem).hide();
    var selected = source.find("option:selected");
    var options = j$("option", source);

    source.after('<dl id="target' + elem + '" class="dropdown"></dl>');
    j$('#target' + elem).append('<dt><a href="#" onclick="return false;"><img src="' 
      + selected.data('preview') + '" alt="sample" />'
      + selected.text() + '<span class="value">' 
      + selected.val() + '</span></a></dt>');
    j$('#target' + elem).append('<dd><ul></ul></dd>');

    options.each(function () {
        j$('#target' + elem + ' dd ul').append('<li><a href="#" onclick="return false;"><img src="' 
          + j$(this).data('preview') + '" alt="sample" />'
          + j$(this).text() + '<span class="value">' 
          + j$(this).val() + '</span></a></li>');
    });

    j$('#target' + elem + '.dropdown dt a').click(function () {
        j$('#target' + elem + '.dropdown dd ul').toggle('blind');
    });

    j$('#target' + elem + ' dd ul').hide();
}

function loadTheme(theme) {}
/**** UTIL FUNCTIONS ****/